package com.jyy.prefabricated.controller;


import com.aliyun.oss.common.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Image;
import com.jyy.prefabricated.common.AjaxResult;
import com.jyy.prefabricated.dto.Pageable;
import com.jyy.prefabricated.dto.StudentCertificateDto;
import com.jyy.prefabricated.entity.StudentCertificate;
import com.jyy.prefabricated.entity.SysUser;
import com.jyy.prefabricated.enums.UserTypeEnum;
import com.jyy.prefabricated.service.BosService;
import com.jyy.prefabricated.service.StudentCertificateService;
import com.jyy.prefabricated.utils.DateUtils;
import com.jyy.prefabricated.utils.PdfUtils;
import com.jyy.prefabricated.utils.QrCodeUtil;
import com.jyy.prefabricated.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 学员证书
 * @version 1.0.0
 * @author: zjj
 */
@Slf4j
@RequestMapping("/api")
@RestController
public class StudentCertificateController {

    @Autowired
    private StudentCertificateService studentCertificateService;

    @Autowired
    private UserUtils userUtils;
    @Autowired
    private BosService bosService;
    /*@Value("${spring.application.url}")
    private String fileUrl;*/
    @Value("${zkz.ewmUrl}")
    private String ewmUrl;
    @Value("${zkz.ewmPath}")
    private String ewmPath;
    /**
     * 新增学员证书
     * @param studentCertificate
     * @return
     */
    @PostMapping("/student-certificate")
    public AjaxResult insert(@Valid @RequestBody StudentCertificate studentCertificate){
        log.info("Rest request to insert studentCertificate:{}",studentCertificate);
        Integer id = studentCertificateService.insert(studentCertificate);
        StudentCertificate result = studentCertificateService.selectById(id);
        return AjaxResult.success(result);
    }

    /**
     * 批量新增学员证书
     * @param dto
     * @return
     */
    @PostMapping("/student-certificate-batch")
    public AjaxResult batchInsert(@Valid @RequestBody StudentCertificateDto dto){
        log.info("Rest request to batch insert studentCertificate:{}",dto);
        List<StudentCertificate> result = studentCertificateService.batchInsert(dto);
        return AjaxResult.success(result);
    }

    /**
     * 批量更新学员证书
     * @param studentCertificates
     * @return
     */
    @PutMapping("/student-certificate-batch")
    public AjaxResult batchUpdate(@Valid @RequestBody List<StudentCertificate> studentCertificates){
        log.info("Rest request to batch update studentCertificate:{}",studentCertificates);
        studentCertificateService.batchUpdate(studentCertificates);
        List<Integer> ids = studentCertificates.stream().map(e->e.getId()).collect(Collectors.toList());
        List<StudentCertificate> result = studentCertificateService.selectByIds(ids);
        return AjaxResult.success(result);
    }

    /**
     * 更新学员证书
     * @param studentCertificate
     * @return
     */
    @PutMapping("/student-certificate")
    public AjaxResult update(@Valid @RequestBody StudentCertificate studentCertificate){
        log.info("Rest request to update studentCertificate:{}",studentCertificate);
        studentCertificateService.update(studentCertificate);
        StudentCertificate result = studentCertificateService.selectById(studentCertificate.getId());
        return AjaxResult.success(result);
    }

    /**
     * 查询学员证书详情
     * @param id
     * @return
     */
    @GetMapping("/student-certificate/{id}")
    public AjaxResult selectById(@PathVariable Integer id){
        log.info("Rest request to find studentCertificate by id:{}",id);
        StudentCertificate result = studentCertificateService.selectById(id);
        return AjaxResult.success(result);
    }

    /**
     * 删除学员证书
     * @param id
     * @return
     */
    @DeleteMapping("/student-certificate/{id}")
    public AjaxResult deleteById(@PathVariable Integer id){
        log.info("Rest request to delete studentCertificate by id:{}",id);
        int row = studentCertificateService.delete(id);
        if(row > 0){
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 分页查询学员证书
     * @param studentName 学员姓名
     * @param idCard 身份证
     * @param certificateName 证书名称
     * @param certificateCode 证书编号
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param pageable 分页信息
     * @return
     */
    @GetMapping("/student-certificate")
    public AjaxResult selectByParams(@RequestParam(required = false, defaultValue = "") String studentName, @RequestParam(required = false, defaultValue = "") String idCard, @RequestParam(required = false, defaultValue = "") String certificateName, @RequestParam(required = false, defaultValue = "") String certificateCode, @RequestParam(required = false, defaultValue = "") String startDate, @RequestParam(required = false, defaultValue = "") String endDate, Pageable pageable){
        log.info("Rest request to find studentCertificate by params studentName:{},idCard:{},certificateName:{},certificateCode:{},startDate:{},endDate:{}",studentName,idCard,certificateName,certificateCode,startDate,endDate);
        List<StudentCertificate> list = new ArrayList<>();
        SysUser user = userUtils.getCurrentUser();
        PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        if(UserTypeEnum.STUDENT.getValue().equals(user.getUserType())){
            list = studentCertificateService.selectByStudentId(user.getStudent().getId());
        } else if(UserTypeEnum.ADMIN.getValue().equals(user.getUserType())){
            list = studentCertificateService.selectByParams(studentName,idCard,certificateName,certificateCode,startDate,endDate);
        }
        PageInfo<StudentCertificate> result = new PageInfo<>(list);
        return AjaxResult.success(result);
    }

    /**
     * 查询学员证书
     * @param studentName 学员姓名
     * @param idCard 身份证
     * @param certificateName 证书名称
     * @param certificateCode 证书编号
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return
     */
    @GetMapping("/student-certificate-list")
    public AjaxResult selectByParams(@RequestParam(required = false, defaultValue = "") String studentName,@RequestParam(required = false, defaultValue = "") String idCard,@RequestParam(required = false, defaultValue = "") String certificateName,@RequestParam(required = false, defaultValue = "") String certificateCode,@RequestParam(required = false, defaultValue = "") String startDate,@RequestParam(required = false, defaultValue = "") String endDate){
        log.info("Rest request to find studentCertificate by params studentName:{},idCard:{},certificateName:{},certificateCode:{},startDate:{},endDate:{}",studentName,idCard,certificateName,certificateCode,startDate,endDate);
        List<StudentCertificate> result = new ArrayList<>();
        SysUser user = userUtils.getCurrentUser();
        if(UserTypeEnum.STUDENT.getValue().equals(user.getUserType())){
            result = studentCertificateService.selectByStudentId(user.getStudent().getId());
        } else if (UserTypeEnum.ADMIN.getValue().equals(user.getUserType())){
            result = studentCertificateService.selectByParams(studentName,idCard,certificateName,certificateCode,startDate,endDate);
        }
        return AjaxResult.success(result);
    }

    /**
     * 下载学时证明返回url
     */
    @RequestMapping(value = "/downloadCertificateUrl", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult downloadCerticateUrl(HttpServletRequest request, HttpServletResponse response, String certificateId) {
        String resultURl = "";
        if (StringUtils.isNullOrEmpty(certificateId)) {
            return AjaxResult.error("参数不能为空");
        }
        SysUser user = userUtils.getCurrentUser();
        StudentCertificate studentCertificate = new StudentCertificate();
        studentCertificate.setStudentId(user.getStudent().getId());
        studentCertificate.setCertificateId(Integer.valueOf(certificateId));
        List<StudentCertificate> studentCertificates = studentCertificateService.selectCertificate(studentCertificate);

        Map<String, String> dataMap = new HashMap<>();
        Map<String, Image> imgMap = new HashMap();
        dataMap.put("idPhoto", studentCertificates.get(0).getStudent().getIdPhoto());
        dataMap.put("name", studentCertificates.get(0).getStudent().getName());
        dataMap.put("identityId", studentCertificates.get(0).getStudent().getIdCard());
        dataMap.put("sex", studentCertificates.get(0).getStudent().getIdCard());
        dataMap.put("dateBirth", DateUtils.formatDate(studentCertificates.get(0).getStudent().getDateBirth(),null));
        dataMap.put("name", "检测员");
        dataMap.put("name", studentCertificates.get(0).getCertificate().getName());
        //dataMap.put("classHours", certificate.getFinishTime().substring(0, 4));
        dataMap.put("certificateDay", DateUtils.formatDate(studentCertificates.get(0).getCertificate().getCreateTime(),null));
        dataMap.put("startMonth", studentCertificates.get(0).getCertificate().getCode());
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/PDF;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + studentCertificates.get(0).getCertificate().getCode() + ".pdf");

        Map<String, Object> o = new HashMap();
        o.put("datemap", dataMap);
        //生成二维码图片 二维码url,二维码保存位置，二维码图片名字
        File file = QrCodeUtil.createQrCode(ewmUrl + studentCertificates.get(0).getCertificate().getCode(), ewmPath, studentCertificates.get(0).getCertificate().getCode());
        /*try {
            //将文件转化为pdf图片
            Image ewmImage = Image.getInstance(PdfUtils.inputstream2Bytes(PdfUtils.file2InputStream(file)));
            imgMap.put("ewmImg", ewmImage);
            o.put("imgmap", imgMap);
            ServletOutputStream out = response.getOutputStream();
            File pdfFile = ResourceUtils.getFile(fileUrl);
            //File pdfFile = ResourceUtils.getFile("classpath:template.pdf");
            try {
                // 创建新的文件，前提是必须文件夹已经存在，即D:/File已经存在，文件夹名字不区分大小写：
                pdfFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            TrainingItemData trainingItemData = mTrainingItemService.queryBasicContent(certificate.getTrainingItem());
            if (trainingItemData.getEduType() == EduType.NewEvidence.getCode()) {
                PdfUtils.generatePdfByTemplateUrl(o, out, "templates/template01.pdf", pdfFile);
            } else if (trainingItemData.getEduType() == EduType.AdultEducation.getCode()) {
                PdfUtils.generatePdfByTemplateUrl(o, out, "templates/template02.pdf", pdfFile);
            } else if (trainingItemData.getEduType() == EduType.Professional.getCode()) {
                PdfUtils.generatePdfByTemplateUrl(o, out, "templates/template03.pdf", pdfFile);
            }

            String random = UUID.randomUUID().toString().replace("-", "");

            String objectName = random + ".pdf";
            resultURl = bosService.putFile(pdfFile, objectName);
            pdfFile.delete();

        } catch (IOException | BadElementException e) {
            e.printStackTrace();
        } finally {
            file.delete();
        }
        responseData.setResultCode(1);
        responseData.setData(resultURl);

        return responseData;*/
        return AjaxResult.error("参数不能为空");
    }
}
